package org.gpf.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 生成验证码的Servlet
 * @author gaopengfei
 * @date 2015-5-8 下午8:33:54
 */
@SuppressWarnings("serial")
public class ImageServlet extends HttpServlet {
	
	// 验证码的可取集合，验证码的位数，验证码的宽度和高度,随机数产生器
	private static char[] chs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
	private static final int NUMBER_OF_CH = 4;
	private static final int IMG_WIDTH = 60;
	private static final int IMG_HEIGHT = 25;
	private static Random r = new Random();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,BufferedImage.TYPE_INT_RGB);	// 实例化BufferedImage
		Graphics g = image.getGraphics();															//　得到画笔
		g.setColor(new Color(255, 240, 240));														// 设置背景颜色
		g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);													// 绘制图片边框
		
		StringBuffer sb = new StringBuffer();														// 保存验证码字符串
		int index;																					// 数组下标
		for (int i = 0; i < NUMBER_OF_CH; i++) {
			index = r.nextInt(chs.length);															// 随机一个下标
			g.setColor(new Color(r.nextInt(150), r.nextInt(250), r.nextInt(100)));	 				// 每一个字符的颜色不同
			g.setFont(new Font("黑体", Font.BOLD, 18));
			g.drawString(chs[index] + "", 15 * i + 3, 20);											// 画出字符
			sb.append(chs[index]);
		}
		
		request.getSession().setAttribute("piccode", sb.toString());								// 保存验证码字符串到session
		ImageIO.write(image, "JPG", response.getOutputStream());									// 向页面中输出验证码
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doGet(request, response);
	}

}
